<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;


// 物流同步查询定时任务 5min
//接口描述：旺店通ERP销售订单的发货状态、物流单号等同步给其他系统，注：”查询物流同步”与“物流同步回写”两个接口配合使用，完成“销售订单发货同步”，仅支持自有/其它平台店铺
// 接口文档: https://open.wangdian.cn/qyb/open/apidoc/doc?path=logistics_sync_query.php
// 执行命令: php artisan sync:LogisticsSyncQuery
class LogisticsSyncQuery extends Command
{
    protected $signature = 'sync:LogisticsSyncQuery';
    protected $description = '同步旺店通物流信息到本地订单表';

    public function handle()
    {
        Log::info('LogisticsSyncQuery', ['开始同步物流信息']);
        $sid = config('services.wdt.sid');
        $appKey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'logistics_sync_query.php';
        $shopNo = config('services.wdt.shopNo');
        $c = new WdtClient($sid, $appKey, $secret, $url);

        $limit = 100;
        $this->syncLogistics($c, $shopNo, $limit);
        $this->info('LogisticsSyncQuery任务执行完毕');
    }

    /**
     * 分页同步物流信息
     */
    private function syncLogistics($client, $shopNo, $limit)
    {
        $pageNo = 0;
        $totalCount = null;
        do {
            $requestParams = [
                'limit' => $limit,
                'shop_no' => $shopNo,
            ];
            Log::info('LogisticsSyncQuery 请求参数', ["pageNo"=>$pageNo,"limit"=>$limit,"shopNo"=>$shopNo,"requestParams"=>$requestParams]);
            $client->putApiParam('limit', $limit);
            $client->putApiParam('shop_no', $shopNo);
            // 分页通过偏移量
            if ($pageNo > 0) {
                $client->putApiParam('offset', $pageNo * $limit);
            }

            $result = $client->wdtOpenApi();
            $resultArr = json_decode($result, true);
            Log::info('LogisticsSyncQuery result', [$resultArr]);
            if (!isset($resultArr['code']) || $resultArr['code'] != 0) {
                Log::error('LogisticsSyncQuery error', [$resultArr]);
                break;
            }
            if ($pageNo === 0 && isset($resultArr['total_count'])) {
                $totalCount = (int)$resultArr['total_count'];
            }
            $trades = $resultArr['trades'] ?? [];
            if (empty($trades)) {
                break;
            }
            $this->processLogisticsList($trades);
            $pageNo++;
            $hasMore = $totalCount !== null ? ($pageNo * $limit < $totalCount) : (count($trades) >= $limit);
        } while ($hasMore);
    }

    /**
     * 处理单页物流数据
     */
    private function processLogisticsList($trades)
    {
        $logisticsList = []; // 收集所有需要回写的记录
        foreach ($trades as $trade) {
            $orderSn = $trade['tid'] ?? '';
            $logisticsNo = $trade['logistics_no'] ?? '';
            $recId = $trade['rec_id'] ?? ''; //旺店通主键,用于logistics_sync_ack回写状态
            $tradeId = $trade['trade_id'] ?? ''; //旺店通订单id
            $platformId = $trade['platform_id'] ?? ''; //旺店通平台id
            $logisticsType = $trade['logistics_type'] ?? '';
            $logisticsName = $trade['logistics_name'] ?? '';
            if (!$orderSn) continue;
            // 匹配本地订单
            $order = DB::table('store_order')->where('order_sn', $orderSn)->first();
            if ($order) {
                // 物流方式/快递公司映射
                $express = '快递';
                $expressCompany = $logisticsName;
                $expressId = 1; // 默认1
                if ($logisticsType == 8) { // 顺丰
                    $expressId = 2;
                    $expressCompany = '顺丰';
                } elseif ($logisticsType == 88) { // 德邦
                    $expressCompany = '德邦';
                } elseif ($logisticsType == 5) { // 圆通/中通
                    $expressCompany = '圆通/中通';
                }
                // 更新物流信息
                DB::table('store_order')->where('order_sn', $orderSn)->update([
                    'rec_id' => $recId,
                    'trade_id' => $tradeId,
                    'platform_id' => $platformId,
                    'tracking_number' => $logisticsNo,
                    'send_status' => 2,//发货状态 1:待发货 2：已发货 3：已收货
                    'express' => $express,
                    'express_company' => $expressCompany,
                    'express_id' => $expressId,
                    'updated_at' => time(),
                ]);
                
                // 收集需要回写的记录
                if (!empty($recId)) {
                    $logisticsList[] = [
                        'rec_id' => $recId,
                        'status' => 0, // 0成功
                        'message' => '',
                    ];
                }
            }
        }
        
        // 批量回写处理
        if (!empty($logisticsList)) {
            Log::info('LogisticsSyncQuery LogisticsSyncAck', ['开始物流同步回写']);
            $sid = config('services.wdt.sid');
            $appKey = config('services.wdt.appkey');
            $secret = config('services.wdt.secret');
            $url = config('services.wdt.url') . 'logistics_sync_ack.php';
            $c = new WdtClient($sid, $appKey, $secret, $url);
            $requestLogisticsSyncAckParams = [
                'logistics_list' => $logisticsList,
            ];
            Log::info('LogisticsSyncQuery LogisticsSyncAck 请求参数', $requestLogisticsSyncAckParams);
            $c->putApiParam('logistics_list', json_encode($logisticsList, JSON_UNESCAPED_UNICODE));
            $result = $c->wdtOpenApi();
            $resultArr = json_decode($result, true);
            Log::info('LogisticsSyncQuery LogisticsSyncAck result', [$resultArr]);
            if (!isset($resultArr['code']) || $resultArr['code'] != 0) {
                Log::error('LogisticsSyncQuery LogisticsSyncAck error', [$resultArr]);
                // 错误处理保持不变
            } else {
                // 全部成功，批量标记 发货状态 1:待发货 2：已发货 3：已收货
                foreach ($logisticsList as $item) {
                    DB::table('store_order')->where('rec_id', $item['rec_id'])->update(['send_status' => 2]);
                }
            }

            $this->info('LogisticsSyncQuery LogisticsSyncAck 回写任务执行完毕');

        }
    }
}